package com.jihui.jihuipicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import static java.lang.Long.parseLong;

@Service
public class PictureUrlUpload extends FileManagerUploadTemplate{
    @Override
    public void validateParams(Object inputSource, String uploadPathPrefix) {
        String fileUrl = (String) inputSource;
        // 校验文件是否为空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl),new BusinessException(ErrorCode.PARAMS_ERROR,"文件URL不能为空"));
        // 校验上传路径前缀
        ThrowUtils.throwIf(uploadPathPrefix == null || uploadPathPrefix.isEmpty(),
                new BusinessException(ErrorCode.PARAMS_ERROR,"上传路径前缀不能为空"));
        // 校验URL是否合法
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件URL不合法");
        }
        // 校验是否是Http或Https请求
        if (!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件URL必须是Http或Https请求");
        }
        HttpResponse httpResponse = null;
        try {
            // 发送head请求获取文件
            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 校验文件类型
            String contentType = httpResponse.header("Content-Type");
            if(StrUtil.isNotBlank(contentType)){
                final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList("image/jpg", "image/webp","image/png", "image/jpeg", "image/gif");
                ThrowUtils.throwIf(!ALLOWED_CONTENT_TYPES.contains(contentType),
                        new BusinessException(ErrorCode.PARAMS_ERROR,"文件类型不正确"));
            }
            // 校验文件大小
            try {
                String contentLengthStr = httpResponse.header("Content-Length");
                if(StrUtil.isNotBlank(contentLengthStr)) {
                    long fileSize = parseLong(contentLengthStr);
                    final long MAX_FILE_SIZE = 1024 * 1024 * 2; // 2M
                    ThrowUtils.throwIf(fileSize > MAX_FILE_SIZE,
                            new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过2M"));
                }
            }catch (NumberFormatException e){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小转换错误");
            }
        }finally {
            // 关闭流
            if (httpResponse != null){
                httpResponse.close();
            }
        }
    }

    @Override
    public String getOriginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.getName(fileUrl);
    }

    @Override
    public void processFile(Object inputSource, File tempFile) throws Exception {
        String fileUrl = (String) inputSource;
        // 下载文件
        HttpUtil.downloadFile(fileUrl, tempFile);
    }
}
